package rc.database.Inflection;

import org.alfresco.model.ContentModel;
import org.alfresco.service.cmr.repository.NodeRef;
import org.alfresco.service.cmr.repository.NodeService;
import org.alfresco.service.cmr.security.PersonService;
import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.extensions.webscripts.AbstractWebScript;
import org.springframework.extensions.webscripts.WebScriptRequest;
import org.springframework.extensions.webscripts.WebScriptResponse;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by IntelliJ IDEA.
 * User: Slejus
 * Date: 13.11.14
 * Time: 09.34
 * To change this template use File | Settings | File Templates.
 */
public class UserInfoInflectionWebScript extends AbstractWebScript{

    private static final Logger logger = Logger.getLogger(UserInfoInflectionWebScript.class);

    private PersonService personService;
    private NodeService nodeService;

    // for Spring injection
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }

    // for Spring injection
    public void setNodeService(NodeService nodeService) {
        this.nodeService = nodeService;
    }

    @Override
    public void execute(WebScriptRequest webScriptRequest, WebScriptResponse webScriptResponse) throws IOException {

        String username =  null;
        username = webScriptRequest.getParameter("user");
        if (username != null && !username.isEmpty()) {
            JSONObject data;
            //String username = org.alfresco.repo.security.authentication.AuthenticationUtil.getFullyAuthenticatedUser();
            logger.debug("USERNAME: " + username);

            if(personService != null && nodeService != null) {
                logger.debug("personService initialized successfully");
                NodeRef personNode = personService.getPerson(username);
                String firstName = nodeService.getProperty(personNode, ContentModel.PROP_FIRSTNAME).toString();
                logger.debug("First Name: " + firstName);
                String lastName = nodeService.getProperty(personNode, ContentModel.PROP_LASTNAME).toString();
                logger.debug("Last Name: " + lastName);
                String jobTitle = nodeService.getProperty(personNode, ContentModel.PROP_JOBTITLE).toString();
                logger.debug("Job Title: " + jobTitle);
                String organization = nodeService.getProperty(personNode, ContentModel.PROP_ORGANIZATION).toString();
                logger.debug("Organization: " + organization);

                try {
                    data = createJSONCallback(InflectUserAlfData(firstName, lastName, jobTitle, organization));
                    String jsonString = data.toString();
                    logger.debug(jsonString);
                    webScriptResponse.setContentType("application/json; charset=utf-8");
                    webScriptResponse.getWriter().write(jsonString);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            } else {
                logger.debug("person service or service registry is null");
            }
        } else {
            logger.debug("BAD USERNAME");
        }

    }
    
    private String inflectPersonInfo(String str, Case wordCase, boolean inflectAllStringWords) {
        String result = "";
        String[] parts = str.split("[,\\s\\-:\\?]");
        int size = parts.length;
        if (inflectAllStringWords) {
            for (int i = 0; i < size; i++) {
                result += Inflector.getCasedWord(parts[i], wordCase);
                if (i != size-1) {
                    result += " ";
                }
            }
        } else {
            String lastWord = parts[size - 1];
            lastWord = Inflector.getCasedWord(lastWord, wordCase);
            parts[size-1] = lastWord;
            for (int i = 0; i < size; i++) {
                result += parts[i];
                if (i != size-1) {
                    result += " ";
                }
            }
        }
        return result;
    }

    private Map InflectUserAlfData(String firstName, String lastName, String jobTitle, String organization) {
        Map userData = new HashMap() ;

        String firstNameKil = inflectPersonInfo(firstName, Case.GENITIVE, true);
        String lastNameKil = inflectPersonInfo(lastName, Case.GENITIVE, true);
        String jobTitleKil = inflectPersonInfo(jobTitle, Case.GENITIVE, true);
        String organizationKil = inflectPersonInfo(organization, Case.GENITIVE, false);

        userData.put("fNameK", firstNameKil);
        userData.put("lNameK", lastNameKil);
        userData.put("jTitleK", jobTitleKil);
        userData.put("orgK", organizationKil);

        String firstNameNau = inflectPersonInfo(firstName, Case.DATIVE, true);
        String lastNameNau = inflectPersonInfo(lastName, Case.DATIVE, true);
        String jobTitleNau = inflectPersonInfo(jobTitle, Case.DATIVE, true);
        String organizationNau = inflectPersonInfo(organization, Case.DATIVE, false);

        userData.put("fNameN", firstNameNau);
        userData.put("lNameN", lastNameNau);
        userData.put("jTitleN", jobTitleNau);
        userData.put("orgN", organizationNau);

        return userData;
    }
    
    private JSONObject createJSONCallback(Map user) throws JSONException {
        JSONObject jsonObj = new JSONObject();
        jsonObj.put("user",user);
        logger.debug(jsonObj);
        return jsonObj;
    }
}
